﻿
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Sharp.DataTransferObject;
using Sharp.Portal;
using Sharp.Portal.Owin;


namespace Ext.Net
{

    /// <summary>
    /// Builder扩展
    /// </summary>
    public static class BuilderExtension
    {
        /// <summary>
        ///     加载预设默认设置
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static FormPanel.Builder Default(this FormPanel.Builder helper)
        {
            var panel = helper.FieldDefaults(fd =>
            {
                fd.LabelSeparator = "：";
                fd.LabelWidth = 110;
                fd.LabelAlign = LabelAlign.Right;
            });

            return panel.BodyPadding(5);
        }

        /// <summary>
        ///     加载预设默认设置
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static FieldContainer.Builder Default(this FieldContainer.Builder helper)
        {
            var panel = helper.FieldDefaults(fd =>
            {
                fd.LabelSeparator = "：";
                fd.LabelWidth = 110;
                fd.LabelAlign = LabelAlign.Right;
            });

            return panel;
        }
        /// <summary>
        /// 树形列表
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="treeNode"></param>
        /// <param name="value"></param>
        /// <param name="valueHiddenName"></param>
        /// <returns></returns>
        public static DropDownField.Builder TreeList(this DropDownField.Builder helper, Node treeNode, object value,
            string valueHiddenName = "OrgId")
        {
            var x = Html.X();


            var dropdownlist = helper
                .AutoId()
                .ValueHiddenName(valueHiddenName)
                .MaxHeight(500)
                .Mode(DropDownMode.ValueText).Component(c => c.Add(
                    x.TreePanel()
                        .Root(treeNode)
                        .RootVisible(false).AutoScroll(true).MinHeight(100).EmptyText("没有数据")
                        .Listeners(li =>
                            li.ItemClick.Handler =
                                "App.Edit.SetDropdownList(#{" + helper.ToComponent().ID + "},record);")
                        .Listeners(li =>
                            li.AfterRender.Fn = @"function(){ var record = this.getStore().getNodeById('" + value +
                                                "'); this.getSelectionModel().select(record); }")
                        .Buttons(x.Button().Text("关闭").ClickEvent("#{" + helper.ToComponent().ID + "}.collapse();"))
                ));

            dropdownlist.Text(string.Empty);
            FindNode(dropdownlist, treeNode, Convert.ToString(value));


            return dropdownlist;
        }
        /// <summary>
        /// 查找节点
        /// </summary>
        /// <param name="dropdownlist"></param>
        /// <param name="orgTree"></param>
        /// <param name="value"></param>
        private static void FindNode(DropDownField.Builder dropdownlist, Node orgTree, string value)
        {
            foreach (var child in orgTree.Children)
            {
                if (child.NodeID == value)
                {
                    dropdownlist.Text(child.Text);
                }

                FindNode(dropdownlist, child, value);
            }

        }
        /// <summary>
        /// 主数据
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="category"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static ComboBox.Builder MasterData(this ComboBox.Builder helper, string category, string value)
        {
            var data = Sharp.Portal.Platform.GetMasterData(category).ToList();
            data.Insert(0, new MasterDataSimpleDTO()
            {
                Name = "　",
                Code = ""
            });

            var combobox = helper;
            combobox.EmptyText("请选择");
            combobox.DisplayField("Name");
            combobox.ValueField("Code");
            combobox.SimpleSubmit(true);
            combobox.SubmitValue(true);

            combobox.QueryMode(DataLoadMode.Local);
            combobox.Editable(false);

            combobox.Store(new Store()
            {
                Data = data
            });

            combobox.Value(value);
            combobox.SelectedItems(value);

            return combobox;
        }
        /// <summary>
        /// 数据源
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="data"></param>
        /// <param name="value"></param>
        /// <param name="displayField"></param>
        /// <param name="valueField"></param>
        /// <returns></returns>
        public static ComboBox.Builder DataSource(this ComboBox.Builder helper, object data, object value,
            string displayField, string valueField)
        {
            var id = "field" + Guid.NewGuid();
            id = id.Replace("-", "");

            var combobox = helper.ID(id);
            combobox.EmptyText("请选择");
            combobox.DisplayField(displayField);
            combobox.ValueField(valueField);
            combobox.Editable(false);

            combobox.QueryMode(DataLoadMode.Local);

            combobox.Store(new Store()
            {
                Data = data,
                AutoDataBind = true
            });
            //combobox.Items(data.Select(d => new ListItem(d.Name, d.Id)));
            //combobox.SelectedItems(value);

            return combobox;
        }
        /// <summary>
        /// 代码项转换文字项
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="category"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static DisplayField.Builder Code2Text(this DisplayField.Builder helper, string category, string code)
        {
            var data = Sharp.Portal.Platform.GetMasterData(category);
            var value = data.FirstOrDefault(x => x.Category == category && x.Code == code)?.Name;
            helper.SubmitValue(false);
            helper.Text(value);
            return helper;
        }
        /// <summary>
        /// 值转文本
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="data"></param>
        /// <param name="value"></param>
        /// <param name="displayField"></param>
        /// <param name="valueField"></param>
        /// <returns></returns>
        public static DisplayField.Builder Value2Text(this DisplayField.Builder helper, object data, object value,
            string displayField, string valueField)
        {

            //if (data == null)
            //{
            //    helper.Text("");
            //    return helper;
            //}
            //foreach (var item in data as IEnumerable)
            //{
            //    var displayFieldProperty = item.GetType().GetProperty(displayField);
            //    var valueFieldProperty = item.GetType().GetProperty(valueField);

            //    if (value.Equals(valueFieldProperty.GetValue(item, null).ToString(),
            //        StringComparison.CurrentCultureIgnoreCase))
            //    {
            //        value = displayFieldProperty.GetValue(item, null).ToString();

            //        helper.Text(value);
            //        return helper;
            //    }
            //}
            //helper.Text(value);

            helper.Text("testing");
            return helper;
        }
        /// <summary>
        /// 节点转换文本
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="data"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static DisplayField.Builder NodeId2NodeText(this DisplayField.Builder helper, Node data, string id)
        {
            if (id.IsNullOrEmpty()) return helper;

            return helper.Text(data.GetText(id).FirstOrDefault());
        }

        private static IEnumerable<string> GetText(this Node data, string id)
        {
            foreach (Node node in data.Children)
            {
                if (node.NodeID == id)
                {
                    yield return node.Text;
                }
                yield return node.GetText(id).FirstOrDefault();
            }
        }

        /// <summary>
        /// 检查表单控件的权限
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="moduleCode"></param>
        /// <returns></returns>
        public static FormPanel.Builder CheckFormItemsPermission(this FormPanel.Builder helper, string moduleCode)
        {
            bool? enableFieldPermissions;
            if (moduleCode.IsNullOrEmpty())
            {
                enableFieldPermissions = false;
            }
            else
            {
                //全局权限是否启用了字段权限
                enableFieldPermissions =
                    Platform.AllPermission().Any(x => x.Code.StartsWith(moduleCode + "_DataList_"));
            }

            if (!enableFieldPermissions.Value)
                return helper;

            foreach (var item in helper.ToComponent().Items)
            {
                if (item is Ext.Net.Field)
                {
                    var field = ((Field) item).Name;
                    var any = SharpUserManager.Current.Permissions.Any(x =>
                        x.Code.Equals($"{moduleCode}_DataList_{field}", StringComparison.CurrentCultureIgnoreCase));
                    if (!any)
                    {
                        item.Hidden = true;
                    }
                }
            }
            return helper;
        }
    }
}